package com.dk.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import utils.RandomPersonInfoUtil;

import java.math.BigDecimal;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.TimeUnit;


public class testController {

    RedisTemplate redisTemplate;

    @RequestMapping("testRedis")
    @ResponseBody
    public String testRedis() {
        //key
        String key = "wangsr0001";
        //阈值
        long top = 200;
        //新访问记录ID
        String value = "15646051140";
        Double score = redisTemplate.opsForZSet().score(key, value);
        //检索是否有旧记录  1.无则插入记录值  2.有则删除 再次插入
        if (null != score) {
            //删除旧的
            redisTemplate.opsForZSet().remove(key, value);
        }
        //加入新的记录，设置当前时间戳为分数score
        redisTemplate.opsForZSet().add(key, value, System.currentTimeMillis());
        //获取总记录数
        Long aLong = redisTemplate.opsForZSet().zCard(key);
        if (aLong > top) {
            //获取阈值200之后的记录  (0,1] 并移除
            redisTemplate.opsForZSet().removeRange(key, 0, aLong - top - 1);
        }
        return "success";
    }
    @RequestMapping("insert")
    @ResponseBody
    public String test1() throws InterruptedException {

        String key = "wangsr0001";
        for (int i = 0; i < 200 ; i++) {
            TimeUnit.SECONDS.sleep(1L);
            String randomChineseName = RandomPersonInfoUtil.getRandomTelephoneNumber();
            redisTemplate.opsForZSet().add(key,randomChineseName,System.currentTimeMillis());
        }
        return "success";
    }
    @RequestMapping("test2")
    @ResponseBody
    public String test2(){
        String key = "wangsr0001";
        long start = 1;
        long size  = 10;
        Set<ZSetOperations.TypedTuple> scoreWithScores = redisTemplate.opsForZSet()
                .reverseRangeWithScores(key, start - 1, size - 1 );
        Iterator<ZSetOperations.TypedTuple> iterator = scoreWithScores.iterator();
        BigDecimal bigDecimal = null;
        while (iterator.hasNext()){
            ZSetOperations.TypedTuple next = iterator.next();
            bigDecimal = BigDecimal.valueOf(next.getScore());
            System.out.println("==》ID： "+next.getValue()+" 时间： "+bigDecimal.toPlainString());
        }
        return "success";
    }
}
